import { Chart } from "chart.js/auto";

/**
 * 可视化聚类结果 + 点击显示人物详情 + 点击空白关闭 + PCA归类依据可视化
 * @param {Array} people 人物数组
 * @param {Array} assignments 聚类分配结果
 * @param {number} k 簇数量
 * @param {Array} projected PCA降维后的二维坐标 [[x1,y1],[x2,y2],...]
 */
export function visualize(people, assignments, k, projected) {
    const ctx = document.getElementById("plot").getContext("2d");

    const colors = ["red", "blue", "green", "orange", "purple", "brown"];
    const datasets = [];

    // 创建簇点数据
    for (let c = 0; c < k; c++) {
        const clusterPoints = people.map((p, i) =>
            assignments[i] === c
                ? { x: projected[i][0], y: projected[i][1], personIndex: i }
                : null
        ).filter(Boolean);

        datasets.push({
            label: `Cluster ${c}`,
            data: clusterPoints,
            backgroundColor: colors[c % colors.length],
            pointRadius: 5,
        });
    }

    // 计算簇中心（PCA坐标）
    const clusterCenters = Array.from({ length: k }, (_, c) => {
        const clusterPoints = projected.filter((_, i) => assignments[i] === c);
        const n = clusterPoints.length;
        const sum = clusterPoints.reduce(
            (acc, [x, y]) => [acc[0] + x, acc[1] + y],
            [0, 0]
        );
        return n > 0 ? [sum[0] / n, sum[1] / n] : [0, 0];
    });

    // 创建或复用详情面板
    let detailPanel = document.getElementById("detail-panel");
    if (!detailPanel) {
        detailPanel = document.createElement("div");
        detailPanel.id = "detail-panel";
        detailPanel.style.position = "fixed";
        detailPanel.style.top = "50px";
        detailPanel.style.right = "20px";
        detailPanel.style.width = "300px";
        detailPanel.style.padding = "15px";
        detailPanel.style.border = "1px solid #ccc";
        detailPanel.style.borderRadius = "8px";
        detailPanel.style.backgroundColor = "#fff";
        detailPanel.style.boxShadow = "0 2px 6px rgba(0,0,0,0.15)";
        detailPanel.style.display = "none";
        document.body.appendChild(detailPanel);
    }

    const chart = new Chart(ctx, {
        type: "scatter",
        data: { datasets },
        options: {
            plugins: { legend: { position: "bottom" } },
            scales: {
                x: { title: { display: true, text: "PCA X" } },
                y: { title: { display: true, text: "PCA Y" } },
            },
            onClick(evt) {
                const points = chart.getElementsAtEventForMode(
                    evt,
                    "nearest",
                    { intersect: true },
                    true
                );
                if (points.length > 0) {
                    const firstPoint = points[0];
                    const datasetIndex = firstPoint.datasetIndex;
                    const index = firstPoint.index;

                    const personIndex = chart.data.datasets[datasetIndex].data[index].personIndex;
                    const person = people[personIndex];

                    const personCluster = assignments[personIndex];
                    const center = clusterCenters[personCluster];
                    const diffX = (projected[personIndex][0] - center[0]).toFixed(3);
                    const diffY = (projected[personIndex][1] - center[1]).toFixed(3);

                    detailPanel.innerHTML = `
            <h3>${person.name}</h3>
            <p><strong>年龄:</strong> ${person.age}</p>
            <p><strong>身高:</strong> ${person.height}</p>
            <p><strong>职业:</strong> ${person.occupation}</p>
            <p><strong>爱好:</strong> ${person.hobby}</p>
            <p><strong>性格:</strong> ${person.personality}</p>
            <hr>
            <p><strong>归类簇:</strong> Cluster ${personCluster}</p>
            <p><strong>簇中心 (PCA):</strong> X ${center[0].toFixed(3)}, Y ${center[1].toFixed(3)}</p>
            <p><strong>与中心差异 (PCA):</strong> ΔX ${diffX}, ΔY ${diffY}</p>
            <canvas id="mini-plot" width="250" height="200"></canvas>
          `;
                    detailPanel.style.display = "block";

                    // 绘制小型簇可视化（PCA坐标）
                    const miniCtx = document.getElementById("mini-plot").getContext("2d");
                    new Chart(miniCtx, {
                        type: "scatter",
                        data: {
                            datasets: [
                                {
                                    label: "簇中心",
                                    data: [{ x: center[0], y: center[1] }],
                                    backgroundColor: "black",
                                    pointRadius: 8,
                                },
                                {
                                    label: person.name,
                                    data: [{ x: projected[personIndex][0], y: projected[personIndex][1] }],
                                    backgroundColor: "red",
                                    pointRadius: 6,
                                },
                            ],
                        },
                        options: {
                            plugins: { legend: { display: false } },
                            scales: {
                                x: { title: { display: true, text: "PCA X" } },
                                y: { title: { display: true, text: "PCA Y" } },
                            },
                        },
                    });
                }
            },
        },
    });

    // 点击空白处隐藏详情面板
    document.addEventListener("click", (e) => {
        if (!e.target.closest("#plot") && !e.target.closest("#detail-panel")) {
            detailPanel.style.display = "none";
        }
    });
}
